import { Component, OnInit, Input, ViewChild, EventEmitter, Output, ElementRef } from '@angular/core';
import { HttpService } from 'lbf';
import { NzMessageService, InputNumber, NzSpinComponent } from 'ng-zorro-antd';

@Component({
  selector: 'app-lb-ud007',
  templateUrl: './lb-ud007.component.html',
  styleUrls: ['./lb-ud007.component.less']
})
export class LbUD007Component implements OnInit {
  // @ViewChild('grsy', {static: false}) grsy: ElementRef;
  @Input() defaultakb001;

  options = [];
  dataUD007: any

  searchtext: string

  isLoad = false;

  canInput = true

  constructor(private lbs: HttpService, private message: NzMessageService, ) { }

  @Output() searchtextChange = new EventEmitter<string>();
  @Output() dataUD007Change = new EventEmitter<string>();

  ngOnInit(): void {
    if(this.defaultakb001) {
      this.queryData(this.defaultakb001)
      .then(options => {
        this.change(this.defaultakb001)
      })
    }
  }

  onclick(val: string) {
    if (val) {
      this.queryData(val);
    }
  }

  onInput(event: KeyboardEvent, val: string) {
    if (event.key === "Enter") {
      if (val) {
        this.queryData(val);
      }
    } else if (event.key === "ArrowUp" || event.key === "ArrowDown") {

    } else {
      this.options = [];
      // let canRun = true

      if(!this.canInput) return 
      this.canInput = false
      setTimeout(() => {
        this.canInput = true
        this.queryData(val)
      }, 50)
    }
  }

  queryData(val: string) {
    return new Promise((resolve, reject) => {
      const tempval = val.replace(/\'/g, "''") 
      this.isLoad = true;
      this.lbs.lbservice('FR_FYCX', {
        para: {
          text: tempval,
        }, page: { 'PAGESIZE': 10, 'PAGEIDX': 1 }
      }).then(resdata => {
        // this.isLoading = false;
        this.isLoad = false;
        if (resdata.code < 1) {
          this.message.error(resdata.errmsg)
          this.options = [];
        } else {
          if (resdata.page.COUNT === 0) {
            this.options = [];
          } else if (resdata.page.COUNT > 0) {
            this.options = resdata.message.list;
          }
        }
        resolve(this.options)
      }).catch(err => {
        reject(err)
      })
    })
    
  }

  change(text: any): void {
    this.dataUD007 = this.options.find(ele => ele.AKB001 === text)

    if(this.dataUD007 || !text) this.dataUD007Change.emit(this.dataUD007);

    this.searchtext = this.dataUD007? this.dataUD007.AKB002: ''
  }

}
